<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.menuName" placeholder="菜单名称" class="filter-item" clearable style="width:200px;" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button v-if="type == 0" v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">新增主菜单</el-button>
    </div>

    <el-table
      ref="dragTable"
      v-loading="listLoading"
      row-key="id"
      :data="list"
      :tree-props="{ children: 'children' }"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="rowClassName"
    >
      <el-table-column label="排序" align="center" width="80px">
        <template slot-scope="{ row }">
          <el-tooltip content="拖拽当前行可进行排序" effect="dark" placement="bottom">
            <span>{{ row.index }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="菜单名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.menuName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单路径" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.path }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="type == 0" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button v-if="row.pid === 0" size="mini" icon="el-icon-plus" type="primary" @click="handleAdd(row)">新增子菜单</el-button>
          <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
      <div v-if="dialogAddSubFormVisible">
        <el-dialog title="新增子菜单" :visible.sync="dialogAddSubFormVisible" :append-to-body="true" :close-on-click-modal="false" :destroy-on-close="true">
          <MenuAddForm ref="menuSubAddForm" :pid="pid" :pid-menu-name="pidMenuName" :pid-total="pidTotal" @close="menuSubAddFormClose" @cancelClose="cancelClose(arguments)" />
        </el-dialog>
      </div>
    </el-table>
    <div v-if="dialogAddFormVisible">
      <el-dialog title="新增主菜单" :visible.sync="dialogAddFormVisible" :append-to-body="true" :close-on-click-modal="false" :destroy-on-close="true">
        <MenuAddForm ref="menuAddForm" :length="total" @close="menuAddFormClose" @cancelClose="cancelClose(arguments)" />
      </el-dialog>
    </div>
    <div v-if="dialogEditFormVisible">
      <el-drawer :visible.sync="dialogEditFormVisible" direction="rtl" size="85%" :append-to-body="true" :destroy-on-close="true" :wrapper-closable="false" :with-header="false">
        <MenuAddForm :id="editId" ref="menuEditForm" :pid="pid" @cancelClose="cancelClose(arguments)" />
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { getSysMenu, deleteSysMenu, editSysMenu } from '@/api/menu';
import waves from '@/directive/waves';
import Sortable from 'sortablejs';
import MenuAddForm from '@/views/sys/menuAdd.vue';

export default {
  name: 'SysMenu',
  components: { MenuAddForm },
  directives: { waves },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 9999,
        menuName: ''
      },
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      dialogAddSubFormVisible: false,
      sortable: null,
      childList: [],
      editId: 0,
      pid: 0,
      pidMenuName: '',
      pidTotal: 0,
      type: null
    };
  },
  created() {
    const { params } = this.$route
    Object.keys(params).forEach(key => {
      this.type = params[key].split(':')[1];
    });
    this.getList();
  },
  methods: {
    async getList() {
      this.listLoading = true;
      await getSysMenu(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        let cnt = 0;
        this.list.forEach(item => {
          const position = this.list.indexOf(item);
          let pidCnt = 0;
          item.children.forEach(child => {
            pidCnt++;
            child.rank = pidCnt;
            this.childList.push(child);
          });
          cnt++;
          item.rank = cnt;
          this.$set(this.list, position, item);
        });
        this.listLoading = false;
        this.$nextTick(() => {
          this.setSort();
        });
      });
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '');
        },
        onEnd: evt => {
          let oldRow = this.list.filter(item => item.index === evt.oldIndex + 1);
          if (oldRow.length === 0) {
            oldRow = this.childList.filter(item => item.index === evt.oldIndex + 1);
          }
          let newRow = this.list.filter(item => item.index === evt.newIndex + 1);
          if (newRow.length === 0) {
            newRow = this.childList.filter(item => item.index === evt.newIndex + 1);
          }
          const oldTop = oldRow[0].rank;
          const newTop = newRow[0].rank;
          oldRow[0].rank = newTop;
          newRow[0].rank = oldTop;
          this.updateSortNum(oldRow[0]);
          this.updateSortNum(newRow[0]);
          this.list = [];
        }
      });
    },
    updateSortNum(item) {
      if (this.type === '0') {
        editSysMenu(item).then(res => {
          if (res.msg !== 'OK') {
            this.$message.error(res.msg);
            return;
          }
          this.getList();
        });
      } else {
        this.$message.error('没有权限排序');
        this.getList();
      }
    },
    rowClassName({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    async handleSearch() {
      this.getList();
    },
    handleCreate() {
      this.dialogAddFormVisible = true;
    },
    async handleDelete(row) {
      await this.$confirm('确定要此条数据吗？', '刪除操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.listLoading = true;
          await deleteSysMenu(row.id).then(res => {
            this.listLoading = false;
            if (res.msg !== 'OK') {
              this.$message.error(res.msg);
              return;
            }
            this.getList();
            this.$message.success('删除成功');
          });
        })
        .catch(() => {});
    },
    handleEdit(row) {
      this.editId = row.id;
      this.pid = row.pid;
      this.dialogEditFormVisible = true;
    },
    handleAdd(row) {
      this.pid = row.menuId;
      this.pidMenuName = row.menuName;
      this.pidTotal = row.children.length;
      this.dialogAddSubFormVisible = true;
    },
    menuAddFormClose() {
      this.dialogAddFormVisible = false;
    },
    menuSubAddFormClose() {
      this.dialogAddSubFormVisible = false;
    },
    cancelClose(data) {
      if (data[1] === 'add') {
        if (data[2] !== null) {
          this.dialogAddSubFormVisible = false;
        } else {
          this.dialogAddFormVisible = false;
        }
      } else {
        this.dialogEditFormVisible = false;
      }
      if (data[0]) {
        if (data[1] === 'add') {
          this.listQuery.menuName = '';
        }
        this.getList();
      }
    }
  }
};
</script>
